﻿
(function () {

    appModule.controller('tenant.views.announcement.index', [
        '$scope', '$uibModal', 'uiGridConstants', 'abp.services.app.announcement', 'appSession',
        function ($scope, $modal, uiGridConstants, announcementService, appSession) {
            var vm = this;

            $scope.$on('$viewContentLoaded', function () {
                Metronic.initAjax();
            });

            vm.loading = false;
            vm.filterText = null;
            vm.curAnnouncement = null;
            vm.permissions = {
                create: abp.auth.hasPermission('Pages.Tenant.Announcement.Create'),
                edit: abp.auth.hasPermission('Pages.Tenant.Announcement.Update'),
                'delete': abp.auth.hasPermission('Pages.Tenant.Announcement.Delete')
            };

            //编辑框输出转码
            htmlDecodeByRegExp = function (str) {
                var s = "";
                if (!str) return "";
                if (str.length == 0) return "";
                s = str.replace(/&amp;/g, "&");
                s = s.replace(/&lt;/g, "<");
                s = s.replace(/&gt;/g, ">");
                s = s.replace(/&nbsp;/g, " ");
                s = s.replace(/&#39;/g, "\'");
                s = s.replace(/&quot;/g, "\"");
                return s;
            }

            var urlAnnouncement = "/api/services/app/announcement/";
            var table = [
                    {
                        title: 'ID',
                        field: 'id'
                    },
                    {
                        title: '标题',
                        field: 'title'
                    },
                    {
                        title: '创建者/发布者',
                        fiele: 'user',
                        template: '# var str=""; if(user!=null){str=user.fullName} # #= str #'
                    },
                    //{
                    //    title: '内容',
                    //    field: 'content',
                    //    template: '#= htmlDecodeByRegExp(content) #'
                    //},
                    {
                        title: '创建时间/发布时间',
                        field: 'creationTime',
                        //format: "{{dataItem.creationTime|date:'yyyy-MM-dd h:m:s'}}"
                        format: '{0:yyyy-MM-dd HH:mm:ss}'
                    },
                    //{
                    //    title: '发布时间 ',
                    //    field: 'lastModificationTime',
                    //    template: '#var str="00:00:00";if(lastModificationTime!==null&&status==1){str=lastModificationTime;}# #= kendo.toString(str,"yyyy-MM-dd H:m:s") #'
                    //},
                    {
                        title: '发布状态',
                        field: 'status',
                        template: '#var str="未发布";if(status==1){str="已发布";}# #= str #'
                    },
            ];
            var fields = {};
            //作家访问时过滤条件和table页面
            if (appSession.user.isEditor == false) {
                fields = { field: "status", operator: "eq", value: 1 };
                table = [
                    {
                        title: 'ID',
                        field: 'id'
                    },
                    {
                        title: '标题',
                        field: 'title'
                    },
                    {
                        title: '创建时间/发布时间',
                        field: 'creationTime',
                        //format: "{{dataItem.creationTime|date:'yyyy-MM-dd h:m:s'}}"
                        format: '{0:yyyy-MM-dd HH:mm:ss}'
                    },
                ];
            }
            var mainGridDataSource = new kendo.data.DataSource({
                type: 'aspnetmvc-ajax',
                transport: {
                    read: {
                        url: urlAnnouncement + "KendoGetAnnouncements",
                        contentType: "application/json",
                        type: "POST"
                    },
                    parameterMap: function (options, operation) {
                        return JSON.stringify(options);
                    }
                },
                pageSize: 10,
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true,
                schema: {
                    data: function (data) {
                        if (data.success === true && data.result != null) {
                            return data.result.data;
                        }
                        return {};
                    },
                    total: function (data) {
                        if (data.success === true && data.result != null) {
                            return data.result.total;
                        }
                        return 0;
                    },
                    model: {
                        id: "id",
                        fields: {
                            id: { type: "number" },
                            creationTime: { type: "date" },
                            lastModificationTime: { type: "date" }
                        }
                    }
                },
                filter: fields
            });

            vm.mainGridOptions = {
                dataSource: mainGridDataSource,
                columnMenu: true,
                reorderable: true,
                resizable: true,
                filterable: true,
                scrollable: true,
                selectable: "multiple",
                allowCopy: true,
                //height: 650,
                change: function (e) {
                    var selectedRows = this.select();
                    for (var i = 0; i < selectedRows.length; i++) {
                        vm.curAnnouncement = this.dataItem(selectedRows[i]);
                    }
                },
                pageable: {
                    buttonCount: 5.0,
                    pageSize: 10,
                    pageSizes: [10, 20, 50, 100],
                    refresh: true
                },
                sortable: {
                    mode: "multiple"
                },
                messages: {
                    commands: {
                        excel: "导出"
                    }
                },
                columns: table,
                detailTemplate:
                    '<div><b>公告标题:</b> #= title #</div>' +
                    '<div><b>创建时间:</b> #= kendo.toString(creationTime,"yyyy-MM-dd H:m:s") #</div>' +
                    '<div><b>发布时间:</b> #var str="00:00:00";if(lastModificationTime!=null&&status==1){str=lastModificationTime;}# #= kendo.toString(str,"yyyy-MM-dd H:m:s") #</div>' +
                    '<div><b>公告内容:</b> #= htmlDecodeByRegExp(content) #</div>'
            };

            function openCreateOreditAnnouncementModal(announcementId) {
                var modalInstance = $modal.open({
                    templateUrl: '~/App/tenant/views/announcement/createOrEditAnnouncement.cshtml',
                    controller: 'tenant.views.announcement.createOrEditAnnouncement as vm',
                    backdrop: 'static',
                    resolve: {
                        announcementId: function () {
                            return announcementId;
                        }
                    }
                });

                modalInstance.result.then(function (result) {
                    vm.mainGridOptions.dataSource.read();
                });
            }
            vm.editAnnouncement = function () {
                console.log(vm.curAnnouncement);
                if (vm.curAnnouncement) {
                    if (vm.curAnnouncement.status == 1) {
                        abp.message.error("该公告已经发布!");
                    }else{
                        openCreateOreditAnnouncementModal(vm.curAnnouncement.id);                
                    }
                } else {
                    abp.message.error("请选择要修改的行!");
                }
            };

            vm.createAnnouncement = function () {
                openCreateOreditAnnouncementModal(null);
            };

            vm.deleteAnnouncement = function () {
                if (vm.curAnnouncement != null && vm.curAnnouncement.id > 0) {
                    if (vm.curAnnouncement.status == 1) {
                        abp.message.error("该公告已经发布!");
                    } else {
                        abp.message.confirm(
                            "是否要删除此条记录！",
                            function (isConfirmed) {
                                if (isConfirmed) {
                                    announcementService.deleteAnnouncement({ id: vm.curAnnouncement.id }).success(function () {
                                        abp.notify.info('删除成功！');
                                        vm.mainGridOptions.dataSource.read();
                                    }).finally(function () {

                                    });
                                }
                            }
                        );
                    }
                } else {
                    abp.message.error("请选择要删除的行");
                }


            };

            vm.SendAnnouncement = function () {
                var modalInstance = $modal.open({
                    templateUrl: '~/App/tenant/views/announcement/sendAnnouncement.cshtml',
                    controller: 'tenant.views.announcement.sendAnnouncement as vm',
                    backdrop: 'static',
                    resolve: {

                    }
                });

                modalInstance.result.then(function (result) {
                    vm.mainGridOptions.dataSource.read();
                });
            }
        }]);
})();
